<template>
    <view>
      <form>
        <xmInfo
        :projectno="dataInfo.projectno"
        :projectname="dataInfo.projectname"
      ></xmInfo>
      <view class="cu-form-group">
        <view class="title">结果</view>
        <!-- <switch :checked="dataInfo.state == 0?true:false"  @change="switch1Change" :disabled="true" /> -->
        <js-radio disabled v-model="dataInfo.state" dict-type="zf_material_check_status "></js-radio>
      </view>
        <view class="cu-form-group">
          <view class="title">抽检日期</view>
          <view>{{ dataInfo.checkdate }}</view>
        </view>
        <view class="cu-form-group" style="min-height: 0"></view>
        <view class="cu-bar bg-white cu-bar1">
          <view class="action">备注</view>
        </view>
  
        <view class="cu-form-group">
          {{ dataInfo.remark || '' }}
        </view>
  
        <view class="cu-form-group" style="min-height: 0"></view>
        <view class="cu-bar bg-white cu-bar1">
          <view class="action"></text>图片上传</view>
        </view>
        <view class="cu-form-group">
          <js-uploadfile
            v-model="dataInfo.dataMap"
            :biz-key="dataInfo.id"
            biz-type="pmMaterialcheck_image"
            :deletable="false" 
            customBtn="false"
          ></js-uploadfile>
        </view>
  
        <!-- <file-upload
          :uploadOptions="uploadOptions"
          :imgList="dataInfo.dImageList"
          @imgListChange="imgListChange"
        ></file-upload> -->
  
  
  
  
        <view class="cu-card"  v-if="dataInfo.pmMaterialchecksList && dataInfo.pmMaterialchecksList.length">
          <view
            class="cu-item shadow"
            v-for="(item, index) in dataInfo.pmMaterialchecksList"
            :key="index"
            v-if="item && item.status != 1"
          >
            <view class="cu-form-group">
              <view class="text-xl text-bold"><view
                  style="
                    display: inline-block;
                    padding: 5px;
                    background: #3e97b0;
                    color: #fff;
                    width: 40px;
                    text-align: center;
                    font-style: italic;
                    font-weight: bold;
                  "
                  class="margin-right-sm"
                >
                  {{ index + 1 }}
                </view>材料编码</view>
              <view class="text-xl text-bold">{{ item.mcode  ? item.mcode : item.metercode }}</view>
            </view>
            <view class="cu-form-group padding">
              <view class="title">材料名称</view>
              <view>{{ item.mname ? item.mname : item.metername }}</view>
            </view>
            <view class="cu-form-group">
              <view class="title">规格型号</view>
              <view>{{ item.mstd }}</view>
            </view>
            <view class="cu-form-group">
              <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>备注</view>
              <view><input placeholder="请输入备注" name="input" v-model="item.remarks"  class="input-align"/></view>
            </view>
            <view class="cu-form-group" style="min-height: 0"></view>
            <view class="cu-bar bg-white cu-bar1">
              <view class="action"><text class="cuIcon-favorfill text-xs text-red"></text>材料图片</view>
            </view>
            <js-uploadfile
                v-model="item.dataMap"
                :biz-key="item.id"
                biz-type="pmMaterialcheck_image_child"
                :deletable="false" 
                customBtn="false"
              ></js-uploadfile>
  
            <!-- <view class="cu-bar bg-white">
              <view class="action"></view>
              <view>
                <text class="cuIcon-deletefill padding text-sl text-red" @click="DelItem(item.pmid?item.pmid:item.id)" ></text>
              </view>
            </view> -->
          </view>
        </view>
        <!-- v-if="flag" -->
        <view style="height: 180rpx" ></view>
        <!-- v-if="flag" -->
        <view class="btn-group cu-bar foot" >
          <!-- <button class="cu-btn bg-green shadow-blur">提交</button> -->
          <view class="flex">
            <js-bpm-button
            v-model="dataInfo.bpm"
            :biz-key="dataInfo.id"
            form-key="material_check"
            @complete="submit"
            :showTraceText="showTraceText"
          ></js-bpm-button>
          </view>
        </view>
      </form>
      <add-detail
        :modalNameDetail="modalNameDetail"
        @modalNameDetailEmit="modalNameDetailEmit"
        @checkedListEmit="checkedListEmit"
        v-if="showAddDetail"
      ></add-detail>
    </view>
  </template>
  <script>
  import addDetail from "./addDetail.vue";
  import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
  import {hasPermission} from '@/common/fire.js'
  export default {
    components: {
      addDetail,
      xmInfo
    },
    data() {
      return {
        uploadOptions: {},
        switchA: false,
        date: new Date().toISOString().substring(0, 10),
        modalName: null,
        modalNameDetail: null,
        showAddDetail: false,
        dataInfo: {
          id: "",
          bpm: {},
          pmMaterialchecksList: [],   
        },
        isSubmitting: false,
        showButton: true,
        flag: hasPermission('material:check:pmMaterialcheck:edit'),
        x: 650, //x坐标
        y: 650, //y坐标
        bpmTaskId: '',
        showTraceText: true,
      };
    },
    onLoad(e) {
        console.log(e,'e--+++++');
      if (!!e.id) {
        this.showButton = true;
        this.getCheckPmMaterialcheckForm(e.id);
        this.bpmTaskId = e['bpm.taskId'];
        if (!this.bpmTaskId) {
					// this.dataInfo.bpm = {};
          this.showTraceText = false;
				}
      }
      if (!!e.xm) {
        this.showButton = true;
        this.dataInfo = JSON.parse(e.xm);
        //   巡检人
        this.dataInfo.state = 4;
      }
    },
    methods: {
      switch1Change(e) {
        if (e.detail.value) {
          this.dataInfo.state = 0;
        } else {
          this.dataInfo.state = 1;
        }
      },
      submit() {
  //       if(!this.dataInfo.checkdate){
  //         this.$u.toast("抽检日期必选");
  //         return;
  //       }
  //       if(!this.dataInfo.remark){
  //         this.$u.toast("备注必填");
  //         return;
  //       }
  //       if (!this.dataInfo.dataMap || !this.dataInfo.dataMap.pmMaterialcheck_image) {
  //         this.$u.toast("图片必传");
  //         return;
  //       }
  //       if (this.dataInfo.pmMaterialchecksList && this.dataInfo.pmMaterialchecksList.length > 0) {
  //         let isValid = true;
  //         let imgValid = true;
  //         console.log(this.dataInfo,'this.dataInfo');
  //         this.dataInfo.pmMaterialchecksList.forEach((item) => {
  
  //           if (!item.remarks && item.status != 1) {
  //             isValid = false;
  //           }
  //           if( (!item.dataMap || !item.dataMap.pmMaterialcheck_image_child)&& item.status != 1){
  //             imgValid = false;
  //           }
  //         });
  //         if (!isValid) {
  //           this.$u.toast("材料明细备注必填");
  //           return;
  //         }
  //         if (!imgValid) {
  //           this.$u.toast("材料图片必传");
  //           return;
  //         }
  //       }
        // if (this.isSubmitting) {
        //   return;
        // } else {
        //   this.isSubmitting = true;
          try {
			  this.dataInfo.status = 4;
            this.$u.api.zfgs
              .checkPmMaterialcheckSave(this.dataInfo)
              .then((res) => {
                if (res.result == "true") {
                  this.$u.toast(res.message);
                  const itemContent = {
                    projectno: this.dataInfo.projectno,
                    projectname: this.dataInfo.projectname,
                  };
                  setTimeout(() => {
                    // uni.navigateTo({
                    //   url:
                    //     "/pages/zfgs/material/check/pmMaterialcheck/list?item=" +
                    //     JSON.stringify(itemContent),
                    // });
					uni.navigateBack({
						delta: 1,
					});
                  }, 500);
                }else{
                  this.$u.toast(res.message);
                }
              });
          } catch (error) {
            this.$u.toast(error.message);
          } finally {
            this.isSubmitting = false;
          }
        // }
      },
  
      DelItem(pmid) {
        uni.showModal({
          title: "",
          content: "确定要删除吗？",
          cancelText: "取消",
          confirmText: "确认",
          success: (res) => {
            if (res.confirm) {
              // 根据item.zhengGaiNo 查找要删除的项
              // let index = this.dataInfo.rectList.findIndex(
              //   (item) => item.id == items.id
              // );
              this.dataInfo.pmMaterialchecksList.map((item) => {
                console.log(item,'item===',pmid);
                if (item.pmid == pmid) {
                  item.status = 1; //状态为1删除
                  // 深度监听dataInfo.rectList
                }else if(item.id == pmid){
                  item.status = 1;
                }
  
              });
              this.$forceUpdate();
              console.log(this.dataInfo.pmMaterialchecksList);
              this.$u.toast("删除成功");
            }
          },
        });
      },
      getCheckPmMaterialcheckForm(id) {
        this.$u.api.zfgs
          .checkPmMaterialcheckForm({
            id: id,
          })
          .then((res) => {
            console.log(res, "res===");
            this.dataInfo = res.pmMaterialcheck;
          });
      },
      SwitchA(e) {
        // this.switchA = e.detail.value
      },
      DateChange(e) {
        this.dataInfo.checkdate = e.detail.value;
        this.$forceUpdate();
      },
      textareaAInput(e) {
        console.log(e.detail.value,'textareaAInput');
        this.dataInfo.remark = e.detail.value;
      },
      addDetail() {
        this.showAddDetail = true;
  
        this.modalNameDetail = "DrawerModalR";
  
        console.log(this.modalNameDetail);
      },
      modalNameDetailEmit(e) {
        this.modalNameDetail = e;
      },
      async checkedListEmit(e) {
        console.log(e, "checkedListEmit", this.dataInfo);
        if (!this.dataInfo.pmMaterialchecksList) {
          this.dataInfo.pmMaterialchecksList = [];
        }
  
        // 将 e 中的每个项目转换为所需格式
  
        let eArray = [];
        e.forEach((item) => {
          eArray.push({
            pmid: item.id,
            metercode: item.mcode,
            metername: item.mname,
            mstd: item.mstd
          });
        });
  
        if (this.dataInfo.pmMaterialchecksList.length == 0) {
          this.dataInfo.pmMaterialchecksList = eArray;
        } else {
  
        // 创建一个新数组用于存放最终结果
          let newArray = [];
  
          // 遍历原始数据
          this.dataInfo.pmMaterialchecksList.forEach((originalItem) => {
            let matched = false; // 标记是否找到了匹配项
  
            // 遍历eArray
            eArray.forEach((updateItem) => {
              if (originalItem.pmid === updateItem.pmid) {
                // 找到匹配项，标记并保存更新后的项目
                matched = true;
                newArray.push(updateItem);
              }
            });
  
            // 如果没有在eArray中找到匹配项，则保留原始项目
            if (!matched) {
              newArray.push(originalItem);
            }
          });
  
          // 将eArray中未在原始列表中找到匹配pmid的项追加到newArray
          eArray.forEach((itemFromEArray) => {
            let exists = newArray.some((item) => item.pmid === itemFromEArray.pmid);
            if (!exists) {
              newArray.push(itemFromEArray);
            }
          });
  
          // 最后，将处理后的数组赋值回原对象
          this.dataInfo.pmMaterialchecksList = newArray;    
  
        }
  
  
  
      },
  
      ViewImage(imageList, e) {
        uni.previewImage({
          urls: imageList,
          current: e.currentTarget.dataset.url,
        });
      },
      ChooseImage() {
        uni.chooseImage({
          count: 4, //默认9
          sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album"], //从相册选择
          success: (res) => {
            if (this.dataInfo.dImageList.length != 0) {
              this.dataInfo.dImageListst = this.dataInfo.dImageList.concat(
                res.tempFilePaths
              );
            } else {
              this.dataInfo.dImageList = res.tempFilePaths;
            }
  
            console.log(this.dataInfo, "this.dataInfo");
            this.$u.toast("上传成功");
          },
        });
      },
    },
  };
  </script>
  <style lang="scss" scoped>
  $all_width: 140rpx;
  $all_height: 140rpx;
  .movable-area {
    z-index: 999;
    height: 97vh;
    width: 650rpx;
    // max-width: 1152rpx;
    // 固定在右边
    top: -150rpx;
    position: fixed;
    right: $all_width;
    // 固定在右下角
    pointer-events: none; //此处要加，鼠标事件可以渗透
    .movable-view {
      width: $all_width;
      height: $all_height;
      pointer-events: auto; //恢复鼠标事件
      .cu-bar{
        width: 320rpx;
      }
    }
  }
  .action {
    color: #303133;
  }
  .cu-form-group {
    flex-wrap: wrap;
  }
  .text-sl {
    font-size: 22px !important;
  }
  .cu-bar {
    min-height: 80px;
  }
  .cu-bar1{
    min-height: 50px !important;
  }
  .cu-btn {
    font-size: 16px;
    height: 40px;
  }
  .foot {
    z-index: 997;
    background: #fff;
  }
  .green {
    color: green;
  }
  .input-align {
    text-align: right;
  }
  .sub-title{
    flex-grow: 1; /* 让右侧内容占据剩余空间 */
    max-width: 200px; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
    word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
  }
  .xm-title{
    flex-basis: 100px; /* 或其他合适的固定宽度，用于左侧标题 */
    flex-shrink: 0; /* 防止标题在小屏幕下收缩 */
    overflow: hidden; /* 可选，防止内容溢出 */
  }
  .text-xsl {
    font-size: 60rpx !important;
  }
  .flex-end {
    display: flex;
    justify-content: flex-end;
  }
  .text-xs {
    font-size: 18rpx !important;
  }
  .cu-item{
    border: 1px solid #39b54a;
  }
  </style>